package com.example.medicine.config;

import com.example.medicine.Bean.yonghu;
import com.example.medicine.Mapper.SystemFunctionMapper;
import com.example.medicine.Mapper.SystemRoleFunctionMapper;
import com.example.medicine.Mapper.SystemRoleMapper;
import com.example.medicine.Mapper.yonghuMapper;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.codec.digest.DigestUtils;
import org.apache.shiro.authc.*;
import org.apache.shiro.authz.AuthorizationInfo;
import org.apache.shiro.authz.SimpleAuthorizationInfo;
import org.apache.shiro.realm.AuthorizingRealm;
import org.apache.shiro.subject.PrincipalCollection;
import org.apache.shiro.util.ByteSource;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.stereotype.Component;


import java.util.Set;
import java.util.stream.Collectors;
@Slf4j
@Component
public class MyRealm extends AuthorizingRealm {
    @Autowired
    private yonghuMapper yonghuMapper;
    @Autowired
    private SystemRoleMapper systemRoleMapper;
    @Autowired
    private SystemRoleFunctionMapper systemRoleFunctionMapper;
    @Autowired
    private SystemFunctionMapper systemFunctionMapper;


//    授权
    @Override protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principals) {
        String username = (String) principals.getPrimaryPrincipal();
        SimpleAuthorizationInfo authorizationInfo = new SimpleAuthorizationInfo();
         //根据用户名从数据库获取用户的角色信息
        String roleName = yonghuMapper.getTypeByUserId(username);
        authorizationInfo.addRole(roleName);
        // 根据角色从 SystemRoleFunctionService 获取对应的功能（权限）ID
        String roleId = systemRoleMapper.getIdByName(roleName);
        Set<String> functionIds = systemRoleFunctionMapper.getFunIdByRoleId(roleId);

        // 将功能（权限）ID转换成权限名字
        Set<String> permissions = functionIds.stream()
                .map(functionId -> systemFunctionMapper.getNameById(functionId))
                .collect(Collectors.toSet());

        authorizationInfo.setStringPermissions(permissions);
//        System.out.println(permissions);
        return authorizationInfo;
    }

    //    认证
    //验证密码操作
    @Override
    protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken authenticationToken) throws AuthenticationException {
        String username = (String) authenticationToken.getPrincipal();


        yonghu user = yonghuMapper.getPasswordByUserid(username);
        if (user == null) {
            throw new UnknownAccountException("用户不存在");
        }
        return new SimpleAuthenticationInfo(user.getUserid(), user.getPassword(), getName());

    }


}
